// src\router\index.ts
import { createRouter, createWebHashHistory } from "vue-router";
import login from "../views/login/index.vue";
import home from "../views/home/index.vue";
import cacheUtils from "@/utils/cacheUtils";

const router = createRouter({
  //  hash 模式。
  history: createWebHashHistory(),
  routes: [
    // 设置首页
    {
      path: "/",
      name: "/",
      //重置到home
      redirect: "/home",
    },
    // 设置login
    {
      path: "/login",
      name: "login",
      component: () => login,
    },
    // 设置home
    {
      path: "/home",
      name: "home",
      component: () => home,
    },

    //测试 demo
    // 设置demo
    {
      path: "/demo",
      component: () => import("../views/demo/index.vue"),
    },
    // 配置helloworld页的路径
    {
      path: "/hello",
      component: () => import("../components/HelloWorld.vue"),
    },
    // 配置helloworld页的路径
    {
      path: "/mockDemo",
      component: () => import("../views/demo/MockDemo.vue"),
    },
    // 配置MockApiDemo页的路径
    {
      path: "/MockApiDemo",
      component: () => import("../views/demo/MockApiDemo.vue"),
    },
    // 配置sassDemo页的路径
    {
      path: "/sassDemo",
      component: () => import("../views/demo/sassDemo.vue"),
    },
    // 配置ipcDemo页的路径
    {
      path: "/ipcDemo",
      component: () => import("@/views/demo/ipcDemo.vue"),
    },
  ],
});

// 假设这是你的检查用户登录状态的函数
const checkLoginStatus = () => {
  // 这里应该是检查用户登录状态的逻辑
  // 例如，检查 localStorage 中的 token
  console.log("检查用户登录状态");
  console.log(cacheUtils.get('userToken'))
  return cacheUtils.get('userToken') !== null;
};

// 路由守卫
router.beforeEach((to, _, next) => {
  const isAuthenticated = checkLoginStatus();

  if (to.path === '/login' && isAuthenticated) {
    // 如果用户尝试访问登录页面，但已经登录，则重定向到主页
    next('/');
  } else if (to.path !== '/login' && !isAuthenticated) {
    // 如果用户尝试访问非登录页面，但未登录，则重定向到登录页面
    next('/login');
  } else {
    // 其他情况，继续正常的导航
    next();
  }
});

export default router;
